package com.zc.im.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.zc.im.model.customer.ZcCustomerServiceModel;
import com.zc.im.model.im.group.ZcImGroupMember;
import com.zc.im.model.im.group.ZcImMsgHistoryModel;
import com.zc.im.model.user.HeartbeatModel;
import com.zc.im.model.user.ZcAdminUser;
import com.zc.im.model.user.ZcUser;
import com.zc.im.netty.global.NettyGlobalData;
import com.zc.im.netty.model.NettyMsgModel;
import com.zc.im.rabbitmq.AmqpConfig;
import com.zc.im.service.customer.CustomerService;
import com.zc.im.service.im.group.ImGroupMemberService;
import com.zc.im.service.im.group.ImMsgHistoryService;
import com.zc.im.service.im.group.ImUnreadNumService;
import com.zc.im.service.user.UserService;
import com.zc.im.util.*;
import com.zc.im.util.properties.RabbitmqProperties;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/21.
 */
@Component
public class ConsumerSend {

    private Logger log = LoggerFactory.getLogger(ConsumerSend.class);

    @Autowired
    private RabbitmqProperties rabbitmqProperties;

    @Autowired
    private AmqpConfig amqpConfig;


    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(amqpConfig.connectionFactory());
        return template;
    }

    /**
     * 接受消息的监听，这个监听会接受消息队列1的消息
     * 针对消费者配置
     * @return*/

    @Bean
    SimpleMessageListenerContainer sendContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setQueues(amqpConfig.sendQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setConnectionFactory(amqpConfig.connectionFactory());
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setQueueNames(rabbitmqProperties.getRabbitSendQueueName());
        container.setMessageListener(new ChannelAwareMessageListener() {
            public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception {
                byte[] body = message.getBody();
                log.error("收到MQ消费消息 : " + new String(body));
                execMqMsgHandle(new String(body));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); //确认消息成功消费
            }
        });
        return container;
    }

    public void execMqMsgHandle(String jsonStr){
        try{
            JSONObject jsonObject = JsonUtils.strToJsonObj(jsonStr);
            if(!jsonObject.containsKey(ImGolbalTypeContext.IM_TYPE)){
                log.error("缺少必要参数 jsonObject：", jsonObject.toJSONString());
                return;
            }
            //设置类型
            String currentMsgType = null;
            //发送者id
            String userId = null;
            //目标id
            String targetUserId = null;
            //内容
            String content = null;
            //群id
            String groupId = null;
            //customer_service  people消息类型   个人或者是小畅
            String sendUserType = null;

            currentMsgType = jsonObject.get(ImGolbalTypeContext.IM_TYPE).toString();
            if(jsonObject.containsKey(ImGolbalTypeContext.IM_USER_ID)){
                userId = jsonObject.get(ImGolbalTypeContext.IM_USER_ID).toString();
            }
            if(jsonObject.containsKey(ImGolbalTypeContext.IM_TARGET_USER_ID)){
                if(jsonObject.get(ImGolbalTypeContext.IM_TARGET_USER_ID) != null){
                    targetUserId = jsonObject.get(ImGolbalTypeContext.IM_TARGET_USER_ID).toString();
                }
            }
            if(jsonObject.containsKey(ImGolbalTypeContext.IM_INFO)){
                content = jsonObject.get(ImGolbalTypeContext.IM_INFO).toString();
            }
            if(jsonObject.containsKey(ImGolbalTypeContext.IM_GROUP_ID)){
                groupId = jsonObject.get(ImGolbalTypeContext.IM_GROUP_ID).toString();
            }
            if(jsonObject.containsKey(ImGolbalTypeContext.IM_SEND_USER_TYPE)){
                sendUserType = jsonObject.get(ImGolbalTypeContext.IM_SEND_USER_TYPE).toString();
            }
            // 与客服绑定
            // 点击与客服聊天 有客服 直接聊天 无客服 分配客服聊天
            if(ImGolbalTypeContext.IM_CUSTOMER_SERVICE.equals(currentMsgType)){
                if(StringUtils.isEmpty(userId)){
                    log.error("分配客服失败,用户ID 为空！");
                    return;
                }
                setCustomerService(userId);
                return;
            }

            //处理消息类型
            handlerMsgTypeAndSendMsg(currentMsgType, userId, targetUserId, content, groupId, sendUserType);

            if (currentMsgType.equals(ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE) || currentMsgType.equals(ImGolbalTypeContext.IM_MSG_TYPE_TO_GROUP)) {
                //持久化消息
                handlerPersistenceMsg(currentMsgType, userId, targetUserId, content, groupId, sendUserType);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }




    public void handlerMsgTypeAndSendMsg(String currentMsgType, String userId, String targetUserId,
                                           String content, String groupId, String sendUserType) {
        String msgType = null;

        switch (currentMsgType) {
            // 个人与企业
            case ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE:
                List<String> member = new ArrayList<>();
                member.add(targetUserId);
                sendMsgToTargetUsers(userId, member, content, ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE, sendUserType);
                break;
            //个人到群组
            case ImGolbalTypeContext.IM_MSG_TYPE_TO_GROUP:
                if(StringUtils.isEmpty(groupId)){
                    log.error("群组ID为空");
                    break;
                }
                // 当前登录用户对象
                // 通过群组ID 查询群组中所有的群成员
                ImGroupMemberService memberService = (ImGroupMemberService) SpringContextUtils.getBeanByClass(ImGroupMemberService.class);
                ZcImGroupMember zcImGroupMemberModel = new ZcImGroupMember();
                zcImGroupMemberModel.setGroupId(Integer.parseInt(groupId));

                List<ZcImGroupMember> groupMemberModels =  memberService.queryAllGroupMember(zcImGroupMemberModel);
                if(groupMemberModels== null|| groupMemberModels.size() == 0){
                    break;
                }
                List<String> groupMembers = new ArrayList<>();
                for(ZcImGroupMember memberModel: groupMemberModels){
                    groupMembers.add(memberModel.getUserId().toString());
                }
                sendMsgToTargetUsers(userId, groupMembers, content, ImGolbalTypeContext.IM_MSG_TYPE_TO_GROUP, sendUserType);
                break;
            case ImGolbalTypeContext.IM_MSG_TYPE_TO_READ_STATUS:
                List<String> readMembers = new ArrayList<>();
                readMembers.add(targetUserId);
                sendMsgToTargetUsers(userId, readMembers, ImGolbalTypeContext.IM_MSG_READ_STATUS_READ, ImGolbalTypeContext.IM_MSG_TYPE_TO_READ_STATUS, sendUserType);
                //消息至未已读
                ImUnreadNumService unreadNumService = (ImUnreadNumService) SpringContextUtils.getBeanByClass(ImUnreadNumService.class);
                unreadNumService.updateUnreadNumToDef(Integer.parseInt(targetUserId), Integer.parseInt(userId),
                        ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE);
                break;

            //企业获得简历
            case ImGolbalTypeContext.IM_MSG_TO_COMPANY_GET_RESUME:
                List<String> resume = new ArrayList<>();
                resume.add(targetUserId);
                sendMsgToTargetUsers(userId, resume, content, ImGolbalTypeContext.IM_MSG_TO_COMPANY_GET_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_COMPANY_GET_RESUME,userId,targetUserId,content,groupId,sendUserType);
                break;
            //个人主动发简历
            case ImGolbalTypeContext.IM_MSG_TO_PEOPLE_GET_RESUME:
                List<String> listGetResume = new ArrayList<>();
                listGetResume.add(targetUserId);
                sendMsgToTargetUsers(userId, listGetResume, content, ImGolbalTypeContext.IM_MSG_TO_PEOPLE_GET_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_PEOPLE_GET_RESUME,userId,targetUserId,content,groupId,sendUserType);
                break;
            //企业接受个人简历
            case ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_RESUME:
                List<String> listCompany = new ArrayList<>();
                listCompany.add(targetUserId);
                String resumeCompanysUrl = ImGolbalTypeContext.IM_MSG_TO_RESUME_URL+content;
                sendMsgToTargetUsers(userId, listCompany, resumeCompanysUrl, ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_RESUME,userId,targetUserId,resumeCompanysUrl,groupId,sendUserType);
                break;
            //个人同意给企业简历
            case ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_RESUME:
                List<String> peopleResumeList = new ArrayList<>();
                peopleResumeList.add(targetUserId);
                String resumePeopleUrl = ImGolbalTypeContext.IM_MSG_TO_RESUME_URL+content;
                sendMsgToTargetUsers(userId, peopleResumeList, resumePeopleUrl, ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_RESUME,userId,targetUserId,resumePeopleUrl,groupId,sendUserType);
                break;
            //企业拒绝接受简历
            case ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_RESUME:
                List<String> resumeList = new ArrayList<>();
                resumeList.add(targetUserId);
                sendMsgToTargetUsers(userId, resumeList, content, ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_RESUME,userId,targetUserId,content,groupId,sendUserType);
                break;
            //个人拒绝给企业简历
            case ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_RESUME:
                List<String> listResume = new ArrayList<>();
                listResume.add(targetUserId);
                sendMsgToTargetUsers(userId, listResume, content, ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_RESUME, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_RESUME,userId,targetUserId,content,groupId,sendUserType);
                break;
            //个人获得电话
            case ImGolbalTypeContext.IM_MSG_TO_GET_PEOPLE_TELEPHONE:
                List<String> listContact = new ArrayList<>();
                listContact.add(targetUserId);
                sendMsgToTargetUsers(userId, listContact, content, ImGolbalTypeContext.IM_MSG_TO_GET_PEOPLE_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_GET_PEOPLE_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            //企业获得电话
            case ImGolbalTypeContext.IM_MSG_TO_GET_COMPANY_TELEPHONE:
                List<String> listTelephone = new ArrayList<>();
                listTelephone.add(targetUserId);
                sendMsgToTargetUsers(userId, listTelephone, content, ImGolbalTypeContext.IM_MSG_TO_GET_COMPANY_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_GET_COMPANY_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            //个人同意电话
            case ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_TELEPHONE:
                List<String> listYesContact = new ArrayList<>();
                listYesContact.add(targetUserId);

                if (content.equals("")) {
                    log.error("发送自己手机号为空");
                }
                sendMsgToTargetUsers(userId, listYesContact, content, ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            //企业同意电话
            case ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_TELEPHONE:
                List<String> listCompanyagreeContact = new ArrayList<>();
                listCompanyagreeContact.add(targetUserId);
                if (content.equals("")) {
                    log.error("企业获得联系方式时，对方手机号为空");
                }
                sendMsgToTargetUsers(userId, listCompanyagreeContact, content, ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            //企业不同意电话
            case ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_TELEPHONE:
                List<String> listCompanyrefuseContact = new ArrayList<>();
                listCompanyrefuseContact.add(targetUserId);
                sendMsgToTargetUsers(userId, listCompanyrefuseContact, content, ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            //个人不同意电话
            case ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_TELEPHONE:
                List<String> listRefuseContact = new ArrayList<>();
                listRefuseContact.add(targetUserId);
                sendMsgToTargetUsers(userId, listRefuseContact, content, ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_TELEPHONE, sendUserType);
                handlerPersistenceMsg(ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_TELEPHONE,userId,targetUserId,content,groupId,sendUserType);
                break;
            default:
                Channel channel = NettyGlobalData.userIdAndChannelMapping.get(userId);
                if (channel == null) {
                    log.error("json错误 发现type不存的格式。userid 没有登录。channel为空");
                    break;
                }
                HeartbeatModel heartbeatModel = new HeartbeatModel();
                heartbeatModel.setType("error");
                heartbeatModel.setResult(String.valueOf(ImGolbalTypeContext.IM_MSG_TYPE_ERROR));
                channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objToStr(heartbeatModel)));
        }
    }
    //设置客服
    public void setCustomerService(String userId){
        if(StringUtils.isEmpty(userId)){
            log.error("分配客服失败,用户ID 为空！");
            return;
        }
        CustomerService customerService = (CustomerService) SpringContextUtils.getBeanByClass(CustomerService.class);
        //查询 客服信息
        Map<String, ZcAdminUser> customerServiceMap = customerService.queryOrSaveUserRelationCustomerService(Integer.parseInt(userId));
        if(customerServiceMap == null || customerServiceMap.size() == 0){
            log.error("数据异常");
            return;
        }
        ZcAdminUser customerServiceUserInfo = customerServiceMap.get(ImGolbalTypeContext.IM_CUSTOMER_SERVICE_INFO);
        if(customerServiceUserInfo == null){
            log.error("数据异常");
            return;
        }
        ZcCustomerServiceModel zcCustomerServiceModel = new ZcCustomerServiceModel();
        zcCustomerServiceModel.setNickName(customerServiceUserInfo.getUserName());
        zcCustomerServiceModel.setUserId(customerServiceUserInfo.getUid());
        if (customerServiceUserInfo.getPicHead() == null) {
            customerServiceUserInfo.setPicHead("http://www.qq745.com/uploads/allimg/150120/1-1501200J427-50.jpg");
        }
        zcCustomerServiceModel.setPortrait(customerServiceUserInfo.getPicHead());//默认头像
        //返回客服信息
        Channel channel = NettyGlobalData.userIdAndChannelMapping.get(userId);
        String msgStr = setNettyMsg(userId, customerServiceUserInfo.getUid().toString(),zcCustomerServiceModel , ImGolbalTypeContext.IM_MSG_TYPE_TO_CUSTOMER_SERVICE);
        channel.writeAndFlush(new TextWebSocketFrame(msgStr));
    }


    /**
     * 组装发送的信息为json
     * @param userId
     * @param targetId
     * @param jsonObject
     * @param type
     * @return
     */
    public String setNettyMsg(String userId, String targetId, Object jsonObject, String type){

        UserService userService = (UserService) SpringContextUtils.getBeanByClass(UserService.class);
        ZcUser sendUser = userService.findUser(Integer.parseInt(userId));

        NettyMsgModel msgModel = new NettyMsgModel();
        msgModel.setSendTime(DateUtils.dateFormatStrYmdHms(new Date()));
        msgModel.setTargetId(targetId);
        msgModel.setUserId(userId);
        msgModel.setInfo(jsonObject);
        msgModel.setType(type);
        if(sendUser != null){
            msgModel.setPicHead(sendUser.getPicHead());
            msgModel.setName(sendUser.getNickname());
        }
        return JsonUtils.objToStr(msgModel);
    }


    /**
     * 发送消息到目标集合
     * 2017-7-8 20:38:30
     * @param targets
     * @param content
     * @return
     */
    private JSONObject sendMsgToTargetUsers(String userId, List<String> targets, String content, String type, String sendUserType) {
        JSONObject json = new JSONObject();
        if(targets == null || targets.size() == 0){
            return json;
        }
		/*//在线用户列表
		ZcUser onlineUser = NettyGlobalData.onlineUser.get(channelHandlerContext.channel().id().toString());
		//在线客服列表
		ZcUser onlineCustomerUser = NettyGlobalData.onlineCustomer.get(channelHandlerContext.channel().id().toString());*/
        //判断数据库中是否存在当前用户
        for(String targetUserId: targets){
            execSendMsg(userId, targetUserId, type, content, sendUserType);
        }
        return json;
    }


    public void execSendMsg(String userId, String targetUserId, String type, String content,String sendUserType){

        if(ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE.equals(type)){
            setMsgUnread(Integer.parseInt(userId), Integer.parseInt(targetUserId), type, sendUserType);
        }
        Channel channel = NettyGlobalData.userIdAndChannelMapping.get(targetUserId);
        if(channel == null){
            return;
        }
        String msg = setNettyMsg(userId, targetUserId, content, type);
        channel.writeAndFlush(new TextWebSocketFrame(msg));
    }


    /**
     * 设置未读消息
     * 2017-7-15 19:17:46
     * @param userId
     * @return
     */
    public void setMsgUnread(Integer userId, Integer targetId, String type, String sendUserType){
        ImUnreadNumService unreadNumService = (ImUnreadNumService) SpringContextUtils.getBeanByClass(ImUnreadNumService.class);
        unreadNumService.saveOrUpdateUnreadNum(userId, targetId, type, sendUserType);
    }


    /**
     * 处理消息持久化
     * @param currentMsgType
     * @param userId
     * @param targetUserId
     * @param content
     * @param groupId
     */
    public void handlerPersistenceMsg( String currentMsgType, String userId, String targetUserId,
                                       String content, String groupId, String sendUserType) {
        ZcImMsgHistoryModel historyModel = new ZcImMsgHistoryModel();
        //内容
        historyModel.setContent(content);
        //消息类型
        historyModel.setMsgAgreementType(currentMsgType);
        if(ImGolbalTypeContext.IM_MSG_TYPE_TO_PEOPLE.equals(currentMsgType)){
        //发送者类型个人
        historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
        //目标者类型个人
        historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
        //目标者id
        historyModel.setTargetObjId(Integer.parseInt(targetUserId));
         //企业获得简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_COMPANY_GET_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
         //个人获得简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_PEOPLE_GET_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        //个人同意简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        //企业同意简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        //个人拒绝简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        //企业拒绝简历
        }else  if (ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_RESUME.equals(currentMsgType)) {
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        //个人获得电话
        else  if (ImGolbalTypeContext.IM_MSG_TO_GET_PEOPLE_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        //企业获得电话
        else  if (ImGolbalTypeContext.IM_MSG_TO_GET_COMPANY_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        //个人同意电话
        else  if (ImGolbalTypeContext.IM_MSG_TO_PEOPLE_AGREE_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        //企业同意电话
        }else  if (ImGolbalTypeContext.IM_MSG_TO_COMPANY_AGREE_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        //个人拒绝电话
        else  if (ImGolbalTypeContext.IM_MSG_TO_PEOPLE_REFUSE_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        //企业拒绝电话
        else  if (ImGolbalTypeContext.IM_MSG_TO_COMPANY_REFUSE_TELEPHONE.equals(currentMsgType)) {
        //消息类型
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
            historyModel.setTargetObjId(Integer.parseInt(targetUserId));
        }
        else{
            //群
            historyModel.setMsgType(ImGolbalTypeContext.IM_MSG_TYPE_GROUP);
            historyModel.setTargetObjType(ImGolbalTypeContext.IM_MSG_TYPE_GROUP);
            historyModel.setTargetObjId(Integer.parseInt(groupId));
        }
        //发送者id
        historyModel.setSourceObjId(Integer.parseInt(userId));
        //发送者类型
        historyModel.setSourceObjType(ImGolbalTypeContext.IM_MSG_TYPE_PEOPLE);
        //重建时间
        historyModel.setCreatedTime(new Date());
        //更新时间
        historyModel.setUpdatedTime(new Date());
        //消息类型未读
        historyModel.setMsgReadStatus(ImGolbalTypeContext.IM_MSG_READ_STATUS_UNREAD);
        //状态
        historyModel.setStatus(ImGolbalTypeContext.STATUS_VALID);

        ImMsgHistoryService imMsgHistoryService = (ImMsgHistoryService) SpringContextUtils.getBeanByClass(ImMsgHistoryService.class);
        imMsgHistoryService.insertImMsgHistory(historyModel);
    }

}
